<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/07
 * Time: 13:29
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\cra;

use app\admin\controller\BaseController;

class IndexController extends BaseController
{
    public function index()
    {
        return $this->fetch("index");
    }

    private $appKey = 'your_app_key';
    private $appSecret = 'your_app_secret';
    private $accessToken = 'your_access_token'; // 获取accessToken的方式请参考阿里巴巴开放平台文档

    // 1688商品采集接口
    public function fetchProductsFrom1688()
    {
        // API请求URL
        $apiUrl = 'https://gw.open.1688.com/openapi/param2/1/com.alibaba.product/alibaba.product.get';

        // 示例商品ID列表，可以根据需要调整
        $productIds = ['123456789', '987654321'];

        $result = [];
        foreach ($productIds as $productId) {
            // 设置请求参数
            $params = [
                'productId' => $productId,
                'access_token' => $this->accessToken,
            ];

            // 发起API请求
            $response = $this->httpGet($apiUrl, $params);

            // 解析响应数据
            $productData = json_decode($response, true);

            if (isset($productData['result']) && $productData['result']['success']) {
                $productInfo = $productData['result']['productInfo'];

                // 将产品数据存入数据库
                $product = new Product();
                $product->product_id = $productInfo['productID'];
                $product->name = $productInfo['subject'];
                $product->price = $productInfo['price']['amount'];
                $product->save();

                $result[] = [
                    'product_id' => $product->product_id,
                    'name' => $product->name,
                    'price' => $product->price,
                ];
            }
        }

        var_dump($result);die;

        return json(['status' => 'success', 'data' => $result]);
    }

}